package handlers

import (
	"fmt"
	"myapi/internal/models"
	"myapi/internal/services"
	"myapi/pkg/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ArticleHandler struct {
	ArticleService *services.ArticleService
}

func NewArticleHandler(ArticleService *services.ArticleService) *ArticleHandler {
	return &ArticleHandler{ArticleService: ArticleService}
}

// Creat 创建文章
func (h *ArticleHandler) Creat(c *gin.Context) {
	var article models.Article
	if err := c.ShouldBindJSON(&article); err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "")
		return
	}
	if err := h.ArticleService.Create(&article); err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, fmt.Errorf("创建失败: %w", err).Error())
		return
	}
	utils.SuccessResponse(c, http.StatusOK, "", article)
}

// Get 获取详情
func (h *ArticleHandler) Get(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "Invalid article ID")
		return
	}
	article, err := h.ArticleService.GetByID(uint(id))
	if err != nil {
		utils.ErrorResponse(c, http.StatusNotFound, err.Error())
		return
	}
	utils.SuccessResponse(c, http.StatusOK, "", article)
}

func (h *ArticleHandler) GetAll(c *gin.Context) {
	page, err := strconv.ParseInt(c.Query("page"), 10, 32)
	if err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "Invalid page")
		return
	}
	pageSize, err := strconv.ParseInt(c.Query("pageSize"), 10, 32)
	if err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "Invalid pageSize")
		return
	}
	article, err := h.ArticleService.GetAll(int(page), int(pageSize))
	if err != nil {
		utils.ErrorResponse(c, http.StatusNotFound, err.Error())
	}
	utils.SuccessResponse(c, http.StatusOK, "", article)
}

// Update 修改内容
func (h *ArticleHandler) Update(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "Invalid article ID")
		return
	}
	var article models.Article
	if err := c.ShouldBindJSON(&article); err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "")
		return
	}
	articleObj, err := h.ArticleService.GetByID(uint(id))
	if err != nil {
		utils.ErrorResponse(c, http.StatusNotFound, err.Error())
	}
	articleObj.Title = article.Title
	articleObj.Content = article.Content
	if err := h.ArticleService.Update(uint(id), articleObj); err != nil {
		utils.ErrorResponse(c, http.StatusNotFound, err.Error())
	}
	utils.SuccessResponse(c, http.StatusOK, "", articleObj)
}

// Delete 删除文章
func (h *ArticleHandler) Delete(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.ErrorResponse(c, http.StatusBadRequest, "Invalid article ID")
	}
	if err := h.ArticleService.Delete(uint(id)); err != nil {
		utils.ErrorResponse(c, http.StatusNotFound, err.Error())
	}
	utils.SuccessResponse(c, http.StatusOK, "删除成功", nil)
}
